package com.cardbaobao.cardbabyclient.widget;


import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.model.FlowChildParam;


/**
 * 自定义ViewGroup
 *
 * @author zad
 */
public class FlowLayout extends ViewGroup implements View.OnClickListener {
    /**
     * 适配器
     */
    private BaseAdapter adapter;
    /**
     * 第一行的行高
     */
    private int firstRowHeight;
    /**
     * 总的高度
     */
    private int totalHeight;
    /**
     * 前一个被单击的位置
     */
    private int lastPos = -1;

    public FlowLayout(Context context) {
        this(context, null);
    }

    public FlowLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public FlowLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.customViewGroup);
        a.recycle();
    }

    /**
     * 重写父类方法，子类layout_margin 属性才会起作用
     */
    @Override
    protected LayoutParams generateLayoutParams(LayoutParams p) {
        return new MarginLayoutParams(p);
    }

    /**
     * 重写父类方法，子类layout_margin 属性才会起作用
     */
    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new MarginLayoutParams(getContext(), attrs);
    }

    /**
     * 重写父类方法，子类layout_margin 属性才会起作用
     */
    @Override
    protected LayoutParams generateDefaultLayoutParams() {
        // 默认
        return new MarginLayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int mPaddingLeft = getPaddingLeft(); // 左内边距
        int mPaddingRight = getPaddingRight(); // 右内边距
        int mPaddingTop = getPaddingTop(); // 顶内边距
        int mPaddingBottom = getPaddingBottom(); // 底内边距

        int mPaintPosX = 0;// 画笔当前x坐标位置
        int mPaintPosY = 0;// 画笔当前y坐标位置
        int childRows = 1;// 孩子行数
        int mViewGroupWidth = MeasureSpec.getSize(widthMeasureSpec);// 当前ViewGroup的总宽度

        int childCount = getChildCount(); // 孩子个数

        /******************** 计算控件高度 ************************/
        for (int i = 0; i < childCount; i++) {
            View childView = getChildAt(i); // 得到孩子View
            if (childView.getVisibility() == View.GONE) {
                continue;
            }
            measureChild(childView, widthMeasureSpec, heightMeasureSpec); // 测量孩子宽高
            int childWidth = childView.getMeasuredWidth(); // 孩子的宽度
            int childHeight = childView.getMeasuredHeight();// 孩子的高度
            if (childWidth > mViewGroupWidth - mPaddingLeft - mPaddingRight) {
                childWidth = mViewGroupWidth - mPaddingLeft - mPaddingRight;
            }
            if (mPaddingLeft + mPaintPosX + childWidth + mPaddingRight > mViewGroupWidth) {
                // 如果横坐标控件不足，则移动到下一行
                mPaintPosX = 0;
                childRows++;
            }
            mPaintPosY = childRows * childHeight;
            mPaintPosX += childWidth;
            if (childRows == 1) {//设置第一行的行高
                firstRowHeight = mPaintPosY;
            }
        }

        /***************** 设置控件测量真实高度，这样的话高度设置match_parent,wrap_content属性便会起作用 ************************/
        int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
        int modeHeight = MeasureSpec.getMode(heightMeasureSpec);
        int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
        int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);
        /**
         * MeasureSpec.EXACTLY 表示 ViewGroup.LayoutParams.MATCH_PARENT 模式
         * MeasureSpec.AT_MOST 表示 ViewGroup.LayoutParams.WRAP_CONTENT 模式
         */
        setMeasuredDimension(modeWidth == MeasureSpec.EXACTLY ? sizeWidth : mViewGroupWidth, modeHeight == MeasureSpec.EXACTLY ? sizeHeight : mPaintPosY + mPaddingTop + mPaddingBottom);
        totalHeight = mPaintPosY + mPaddingTop + mPaddingBottom;
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {

        int mPaddingLeft = getPaddingLeft(); // 左内边距
        int mPaddingRight = getPaddingRight(); // 右内边距
        int mPaddingTop = getPaddingTop(); // 顶内边距

        int mViewGroupWidth = getMeasuredWidth();// 当前ViewGroup的总宽度
        int mPaintPosX = left = 0; // 当前绘图光标横坐标位置
        int mPaintPosY = 0; // 当前绘图光标纵坐标位置

        int childCount = getChildCount(); // 孩子个数

        for (int i = 0; i < childCount; i++) {
            View childView = getChildAt(i); // 得到孩子View
            if (childView.getVisibility() == View.GONE) {
                continue;
            }
            int childWidth = childView.getMeasuredWidth(); // 孩子的宽度
            int childHeight = childView.getMeasuredHeight();// 孩子的高度

            if (childWidth > mViewGroupWidth - mPaddingLeft - mPaddingRight) {
                childWidth = mViewGroupWidth - mPaddingLeft - mPaddingRight;
            }
            /********************** 绘制孩子View ****************************/

            if (mPaddingLeft + mPaintPosX + childWidth + mPaddingRight > mViewGroupWidth) {
                // 如果横坐标控件不足，则移动到下一行
                mPaintPosX = left;
                mPaintPosY += childHeight;
            }
            // 绘制孩子ChildView
            childView.layout(mPaddingLeft + mPaintPosX, mPaddingTop + mPaintPosY, mPaddingLeft + mPaintPosX + childWidth, mPaddingTop + mPaintPosY + childHeight);
            // 将当前光标移动到已经绘制的横坐标位置
            mPaintPosX += childWidth;
        }
    }

    public void setAdapter(BaseAdapter adapter) {
        this.removeAllViews();
        this.adapter = adapter;
        for (int i = 0; i < adapter.getCount(); i++) {
            View child = adapter.getView(i, null, null);
            child.setTag(i);
            addView(child); // 将适配器中的childview添加到ViewGroup中
            child.setOnClickListener(this);
        }
        postInvalidate();
    }

    /**
     * 设置子控件中的TextView背景色和字体颜色(根布局是LinearLayout)
     *
     * @param childOne
     * @param childTwo
     */
    public void setChildTextViewBackground(FlowChildParam childOne, FlowChildParam childTwo) {
        if (childOne != null && childTwo != null) {
            LinearLayout oneChidView = (LinearLayout) getChildAt(childOne.getPosition());
            LinearLayout twoChidView = (LinearLayout) getChildAt(childTwo.getPosition());
            if (oneChidView != null) {
                if (oneChidView.getChildAt(0) instanceof TextView) {
                    TextView textView = (TextView) oneChidView.getChildAt(0);
                    textView.setBackgroundResource(childOne.getBgRes());
                    textView.setTextColor(childOne.getTxtColor());
                }
            }
            if (twoChidView != null) {
                if (twoChidView.getChildAt(0) instanceof TextView) {
                    TextView textView = (TextView) twoChidView.getChildAt(0);
                    textView.setBackgroundResource(childTwo.getBgRes());
                    textView.setTextColor(childTwo.getTxtColor());
                }
            }
        }
    }

    public int getFirstRowHeight() {
        return firstRowHeight;
    }

    public int getTotalHeight() {
        return totalHeight;
    }

    public void setOnFlowItemClickListener(OnFlowItemClickListener onFlowItemClickListener) {
        this.onFlowItemClickListener = onFlowItemClickListener;
    }

    private OnFlowItemClickListener onFlowItemClickListener;

    @Override
    public void onClick(View child) {
        if (onFlowItemClickListener != null) {
            if (child.getTag() instanceof Integer) {
                int position = (int) child.getTag();
                onFlowItemClickListener.onFlowItemClick(FlowLayout.this, position, lastPos);
                lastPos = position;
            }
        }
    }

    public interface OnFlowItemClickListener {
        /**
         * @param currentPos 当前位置
         * @param lastPos    上一个位置
         */
        void onFlowItemClick(View v, int currentPos, int lastPos);
    }
}
